﻿create PROCEDURE Sync.SP_LoanIntstallmentWarnings_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanIntstallmentWarnings_Temp TABLE 
		(
			LoanIntstallmentWarningID UniqueIdentifier,
			[LoanExecutionInstallmentID] uniqueidentifier,
				[WarningDate] datetime,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanIntstallmentWarnings_Temp 
	   SELECT	Tbl.Col.value('LoanIntstallmentWarningID[1]','uniqueidentifier') LoanIntstallmentWarningID,
                Tbl.Col.value('LoanExecutionInstallmentID[1]', 'uniqueidentifier') [LoanExecutionInstallmentID],
Tbl.Col.value('WarningDate[1]', 'datetime') [WarningDate],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanIntstallmentWarnings') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanIntstallmentWarnings] ([LoanIntstallmentWarningID],[LoanExecutionInstallmentID],[WarningDate])
	SELECT t.[LoanIntstallmentWarningID],t.[LoanExecutionInstallmentID],t.[WarningDate]
	FROM  @LoanIntstallmentWarnings_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanIntstallmentWarnings_Tracking s
        WHERE t.LoanIntstallmentWarningID = s.LoanIntstallmentWarningID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanIntstallmentWarnings]
	SET [LoanIntstallmentWarnings].[LoanExecutionInstallmentID] = t.[LoanExecutionInstallmentID],[LoanIntstallmentWarnings].[WarningDate] = t.[WarningDate] 
	FROM [dbo].[LoanIntstallmentWarnings] s JOIN @LoanIntstallmentWarnings_Temp t 
    ON t.LoanIntstallmentWarningID = s.LoanIntstallmentWarningID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanIntstallmentWarnings_Tracking r
				  WHERE t.LoanIntstallmentWarningID = r.LoanIntstallmentWarningID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanIntstallmentWarnings]
    FROM @LoanIntstallmentWarnings_Temp t JOIN [dbo].[LoanIntstallmentWarnings] s
    ON t.LoanIntstallmentWarningID = s.LoanIntstallmentWarningID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











